import axios from 'axios'
import {useAuthStore} from '@/stores/auth'
import { ElMessage } from 'element-plus'

const request = axios.create({
    //baseURL: import.meta.env.VITE_API_BASE_URL,
    baseURL: '/api',
    timeout: 10000
})

request.interceptors.request.use(
    (config) => {
        const authStore = useAuthStore()
        if (authStore.token) {
            config.headers.Authorization = `Bearer ${authStore.token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    (response) => {
        const {config, data} = response
        const {code, msg} = response.data
        if(!config.url.startsWith('/oauth2/getRedirectUri')){
            if(code !== 200){
                ElMessage.error(msg || '请求失败')
                return Promise.reject(new Error(msg || '请求失败'))
            }
            return response.data
        }else{
            return response.data
        }
    },
    (error) => {
        const errorMessage = error.response?.data?.msg
            || error.message
            || '网络异常，请稍后再试'
        ElMessage.error(errorMessage)

        if (error.response?.status === 401) {
            const authStore = useAuthStore()
            authStore.logout()
            window.location.href = '/'
        }
        return Promise.reject(error)
    }
)

export default request